package com.example.videoplayer

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.File
import java.net.URL
import java.util.concurrent.Executors
import java.util.concurrent.Future
class FileDownloader(private val context: Context) {
    private fun downloadFile(url: String, destination: String):File {
        val file = File(destination)
        file.outputStream().use { output ->
            URL(url).openStream().use { input ->
                input.copyTo(output)
            }
        }
        return file
    }

    fun downloadFiles(fileDataList: List<MainActivity.FileObj>,callback: () -> Unit) {
        val downloadDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath)
        if (!downloadDir.exists()) {
            downloadDir.mkdirs()
        }
        val executor = Executors.newFixedThreadPool(fileDataList.size)
        val futures = ArrayList<Future<File>>()
        for (url in fileDataList) {
            val fileDestination = File(downloadDir, url.name).absolutePath
            val suffix = url.url.substring(url.url.lastIndexOf('.'))
            val future = executor.submit<File> { downloadFile(url.url, fileDestination + suffix) }
            futures.add(future)
        }

        executor.shutdown()

        // 使用线程等待所有下载任务完成
        for (future in futures) {
            future.get()
        }

        // 所有文件下载完成，执行回调
        callback.invoke()
    }
}